import re
import time
from openpyxl.workbook import Workbook

from logger.logger import Log
from core.serial_port import SerialPort
import api.config


# 测试网关在不同温度环境下重启的稳定性(主动下发reboot指令) -- 串口连接
# @AUTHOR -- 陈选 -- 2024-04-18
class testConnect:
    def start(self):
        #   ['Gateway']['SerialPort'] = COM3  ['Gateway']['SerialBitrate'] = 115200
        self.serial = SerialPort(self.serial_port, self.serial_bitrate)
        start_time = time.time()
        total_run_time = api.config.Config.arg['TestCase']['serRebootTime']
        # 登陆超时时间
        login_timeout = 30  # 5分钟
        try:
            # 串口对象被成功创建并打开，并且获取了当前可读取的字节数
            self.serial.open()
        except Exception as e:
            Log.logger.error("网关串口打开失败，请检查接线与配置文件！！！")
        if self.serial.is_open():
            Log.logger.info("Open Gateway Serial Successful")
            self.is_connect = True
            # 串口是否登录
            while not self.login_by_serial:
                self.serial_login()
            time.sleep(2)
            self.serial.write('reboot\n')

            # 每隔十分钟发送一次重启命令
            while True:
                # 如果当前时间超过了总运行时间，则终止程序
                if time.time() - start_time >= total_run_time:
                    break

                time.sleep(30)  # 等待十分钟
                self.serial.write('reboot\n')

                time.sleep(5)
                tempData = self.serial.read(20000).decode('utf-8')

                # 登录超时计时器
                login_start_time = time.time()
                while not self.serial_login_SecondData:
                    self.serial_login_Second()

                    # 检查是否超过登录超时时间
                    if time.time() - login_start_time >= login_timeout:
                        break

                time.sleep(2)
                if self.serial_login_SecondData:
                    self.rebootList.append([get_time(), "Pass"])
                else:
                    self.rebootList.append([get_time(), "Failed", tempData])

                self.write_to_excel()

    def write_to_excel(self):
        # 创建一个新的工作簿
        wb = Workbook()
        # 选择活动工作表
        ws = wb.active
        # 设置第一列和第二列的宽度
        ws.column_dimensions['A'].width = 20  # 设置第一列宽度为20
        ws.column_dimensions['B'].width = 20  # 设置第二列宽度为20
        ws.column_dimensions['A'].height = 20  # 设置第一列宽度为20
        ws.column_dimensions['B'].height = 20  # 设置第二列宽度为20
        # 写入数据
        ws.append(['重启时间', '测试结果'])
        for item in self.rebootList:
            ws.append(item)
        # 保存工作簿
        wb.save('report/' + get_time() + '_' + "Reboot.xlsx")

    # 用于串口登录
    def serial_login(self):
        # 根据输入的数据类型(输入是否包含 HEX )，进行不同的处理方式，最终将处理后的数据写入到串口中
        self.serial.write('\n')
        self.data = self.serial.read(1000).decode('utf-8')
        print(self.data)
        # 串口登录的账号密码输入
        if "OpenWrt login:" in self.data:
            self.serial.write('root\n')
            self.data = self.serial.read(1000).decode('utf-8')
            print(self.data)
            if "Password:" in self.data:
                self.serial.write('admin\n')
                self.data = self.serial.read(1000).decode('utf-8')
                print(self.data)
        # 串口登录网关成功
        elif 'root@OpenWrt:' in self.data:
            self.login_by_serial = True
            Log.logger.info("串口登录网关成功\r\n")
        else:
            self.serial.write('\n')
            self.data = self.serial.read(1000).decode('utf-8')

    def serial_login_Second(self):
        # 根据输入的数据类型(输入是否包含 HEX )，进行不同的处理方式，最终将处理后的数据写入到串口中
        self.serial.write('\n')
        self.data = self.serial.read(3000).decode('utf-8')
        # 串口登录的账号密码输入
        if "OpenWrt login:" in self.data:
            self.serial.write('root\n')
            self.data = self.serial.read(1000).decode('utf-8')
            print(self.data)
            if "Password:" in self.data:
                self.serial.write('admin\n')
                self.data = self.serial.read(1000).decode('utf-8')
                print(self.data)
        # 串口登录网关成功
        elif 'root@OpenWrt:' in self.data:
            self.serial_login_SecondData = True
            Log.logger.info("串口登录网关成功\r\n")
        else:
            self.serial.write('\n')
            self.data = self.serial.read(1000).decode('utf-8')

    def send_msg(self, msg):
        msg = msg.replace('\r', '').replace('\n', '')
        # 找到第一个左花括号{之前的部分
        head = re.findall('.+(?={)', msg)[0]
        # 找到第一个左花括号{和右花括号}之间的部分
        body = re.findall('{.*}', msg)[0]
        msg = head + body.replace(' ', '')
        # 检查连接
        if self.is_connect:
            if self.is_ssh_con:
                self.invoke.send((msg + '\n').encode())
                log = "[Send Gateway Msg ]: {}".format(msg.encode())
                Log.logger.info(log)
                time.sleep(1)
            else:
                self.serial.write(msg + '\n')
                log = "[Send Gateway Msg ]: {}".format(msg.encode())
                Log.logger.info(log)
                self.read_serial_data = True

    def close(self):
        if self.is_ssh_con:
            self.ssh.close()
        else:
            self.serial.close()

    def __init__(self):
        self.is_connect = False
        self.pid = None
        self.pid_kill = True
        self.data = str()
        self.serial = None
        self.invoke = None
        self.end_str = api.config.Config.arg['TestCase']['endstr']
        self.exepath = api.config.Config.arg['TestCase']['exepath']
        self.exe = api.config.Config.arg['TestCase']['exe']
        self.is_ssh_con = True if api.config.Config.arg['Gateway']['Connect'] == 'SSH' else False
        self.login_by_serial = False
        self.read_serial_data = False
        self.serial_login_SecondData = False
        self.rebootList = []
        # 串行端口的名称或者设备文件名
        self.serial_port = api.config.Config.arg['Gateway']['SerialPort']
        # 波特率
        self.serial_bitrate = int(api.config.Config.arg['Gateway']['SerialBitrate'])


def get_time() -> str:
    return time.strftime("%Y%m%d_%H_%M_%S", time.localtime())